package com.sunmouse.toolkit.fragment.bluetooth;


import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.sunmouse.toolkit.R;
import com.sunmouse.toolkit.bean.BluetoothBean;
import com.sunmouse.toolkit.fragment.BaseFragment;
import com.sunmouse.toolkit.receiver.BluetoothReceiver;
import com.sunmouse.toollib.receiver.OnReceiveListener;
import com.sunmouse.toollib.utils.LogUtils;
import com.sunmouse.toollib.utils.system.PermissionUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class BluetoothFragment extends BaseFragment {

    @BindView(R.id.m_list)
    RecyclerView mList;
    @BindView(R.id.scan_btn)
    Button scanBtn;
    Unbinder unbinder;
    private BluetoothReceiver mReceiver;

    private ArrayList<BluetoothBean> mData;
    private com.sunmouse.toolkit.adapter.BluetoothAdapter mAdapter;
    private BluetoothAdapter mBluetooth;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_bluetooth, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void init() {
        //register bluetooth receiver
        this.mReceiver = new BluetoothReceiver();
        getActivity().registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        this.mReceiver.setOnReceiveListener(mOnReceiveListener);
        this.mBluetooth = BluetoothAdapter.getDefaultAdapter();

        this.mData = new ArrayList<>();
        this.mAdapter = new com.sunmouse.toolkit.adapter.BluetoothAdapter(mData, getActivity());
        this.mList.setLayoutManager(new LinearLayoutManager(getActivity()));
        this.mList.setAdapter(mAdapter);

        requestPer();
    }

    /**
     * request permission
     */
    private void requestPer() {
        String per = Manifest.permission.BLUETOOTH;
        if (!PermissionUtil.isPermitted(getActivity(), per)) {
            PermissionUtil.requestPermission(getActivity(), per, 5);
            return;
        }
        mBluetooth.startDiscovery();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mReceiver);
    }

    /**
     * receiver listener
     */
    private OnReceiveListener mOnReceiveListener = new OnReceiveListener() {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtils.i("Bluetooth", "---find new devices");
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                BluetoothBean bean = new BluetoothBean();
                bean.setName(device.getName());
                bean.setAddress(device.getAddress());
                mData.add(bean);
                mAdapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 5) {
            boolean result = grantResults[0] == PackageManager.PERMISSION_GRANTED;
            if (!result) getActivity().finish();
            mBluetooth.startDiscovery();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
